package models

import (
	"gitee.com/ai-love-save/ai-love-save-back/app/daos"
	"gitee.com/ai-love-save/ai-love-save-back/app/entity"
	"gitee.com/ai-love-save/ai-love-save-back/app/utils"
	"github.com/google/wire"
	"go.uber.org/zap"
	"regexp"
)

var UserSet = wire.NewSet(NewUser, wire.Bind(new(IUser), new(*User)))

type IUser interface {
	Login(username, password string) (error, *UserLoginSchema)
}

type User struct {
	Logger  *zap.Logger
	UserDao *daos.User
	Crypto  *utils.Crypto
}

type UserLoginSchema struct {
	UserName string `json:"id"`
}

func (u *User) getUserByUserName(uid string) (error, *entity.User) {
	params := daos.UserGetParams{
		Phone: uid,
	}
	// 调取数据库数据
	err, temp := u.UserDao.Get(params)
	if err != nil {
		return err, nil
	}

	// 接口转型
	tempInfo, ok := temp.(entity.User)
	if !ok {
		return utils.ErrTypeMismatch, nil
	}

	return nil, &tempInfo
}

func (u *User) Login(username, password string) (error, *UserLoginSchema) {
	u.Logger.Info("开始进行登录处理", zap.String("username", username))
	var res *entity.User

	if match, _ := regexp.MatchString("^1[3-9]\\d{9}", username); match {
		params := daos.UserGetParams{
			Phone: username,
		}
		// 调取数据库数据
		err, temp := u.UserDao.Get(params)
		if err != nil {
			return err, nil
		}

		// 接口转型
		tempInfo, ok := temp.(entity.User)
		if !ok {
			return utils.ErrTypeMismatch, nil
		}
		res = &tempInfo
	} else {
		return utils.ErrParamsMiss, nil
	}

	temp := u.Crypto.MD5(password)
	//fmt.Println(temp==res.Password)
	if temp != res.Password {
		u.Logger.Debug("密码打印",
			zap.String("name", res.Name),
			zap.String("temp", temp),
			zap.String("password", res.Password),
		)
		return utils.ErrPasswordMismatch, nil
	}

	return nil, &UserLoginSchema{
		UserName: res.Name,
	}
}

func NewUser(userDao *daos.User, logger *zap.Logger) *User {
	return &User{
		UserDao: userDao,
		Logger:  logger,
	}
}
